package com.common.tools.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.api.annontation.Authority;
import com.common.api.annontation.ServiceLog;
import com.common.api.enums.OperateEnum;
import com.common.api.model.PageModel;
import com.common.tools.api.dto.DictItemDto;
import com.common.tools.api.service.DictItemService;
import com.common.tools.po.DictItemPo;
import com.common.tools.util.BaseBusyServiceUtil;
import com.common.web.annotation.ControllerRequest;
import com.common.web.controller.BaseController;
import com.common.web.dto.request.FuzzyPageDTO;
import com.common.web.dto.response.RestResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典表前端控制器
 * </p>
 *
 * @author zhuchao
 */
@ServiceLog
@ControllerRequest("/dictItem/")
@Api(tags = "系统工具-字典项表服务接口")
public class DictItemController extends BaseController {

    @Autowired
    private DictItemService dictItemService;


    /**
     * 根据dictTypeCode查询字典项（多个），
     * 返回类型：map
     * 查询多个字典分类下的字典项
     */
    @ApiOperation("批量查询字典项")
    @RequestMapping(value = "queryMapByDictTypeCode")
    public RestResponse queryMapByDictTypeCode(@RequestBody List<String> dictTypeCodeList) {
        // 验证输入参数是否为空或含有非法字符
        if (CollectionUtils.isEmpty(dictTypeCodeList) || dictTypeCodeList.stream().anyMatch(StringUtils::isBlank)) {
            return RestResponse.failure("请选择要查询的字典项所属的字典分类！").setData(null);
        }
        // 对传入的列表去重，避免不必要的数据库查询
        List<String> distinctDictTypeCodeList = dictTypeCodeList.stream().distinct().collect(Collectors.toList());
        Map<String, List<DictItemPo>> dictItemMap = new HashMap<>();
        try {
            // 1、先查询出字典分类对应的所有字典值的集合
            List<DictItemPo> dictItemPoList = dictItemService.list(Wrappers.lambdaQuery(DictItemPo.class)
                    .in(DictItemPo::getDictTypeCode, distinctDictTypeCodeList));
            if (CollectionUtils.isNotEmpty(dictItemPoList)) {
                dictItemMap = dictItemPoList.stream()
                        .collect(Collectors.groupingBy(DictItemPo::getDictTypeCode));
            }
            return RestResponse.success("查询指定字典分类下的字典项成功！").setData(dictItemMap);
        } catch (Exception e) {
            return RestResponse.failure("查询字典项失败，请稍后重试！").setData(null);
        }
    }


    /**
     * 查询所有字典信息
     *
     * @param fuzzyPageDTO
     * @return
     */
    @ApiOperation(value = "查询所有字典项")
    @RequestMapping(value = "queryList")
    public RestResponse queryList(@RequestBody FuzzyPageDTO fuzzyPageDTO) {
        try {
            PageModel<DictItemDto> page = dictItemService.queryList(fuzzyPageDTO);
            return RestResponse.success("字典项查询成功!").setData(page);
        } catch (Exception e) {
            return RestResponse.failure("字典项查询失败：" + e.getMessage());
        }
    }


    /**
     * 保存字典信息
     *
     * @param dto
     * @return
     */
    @RequestMapping(value = "save")
    @ApiOperation(value = "保存字典项")
    @Authority(authous = {"dictType/dictTypeEdit"})
    public RestResponse save(@RequestBody DictItemDto dto) {
        String operation = StringUtils.isBlank(dto.getId()) ? OperateEnum.addDictItem.getEnumName() : OperateEnum.updateDictItem.getEnumName();
        try {
            executeDictItemOperation(dto, operation);
            return RestResponse.success(operation + "成功！");
        } catch (Exception e) {
            return RestResponse.failure(operation + "失败：" + e.getMessage());
        }
    }

    private void executeDictItemOperation(DictItemDto dto, String operation) {
        if (OperateEnum.addDictItem.getEnumName().equals(operation)) {
            logOperateDetails(OperateEnum.addDictItem, getUserCode(), dto);
            dictItemService.add(dto);
        } else if (OperateEnum.updateDictItem.getEnumName().equals(operation)) {
            logOperateDetails(OperateEnum.updateDictItem, getUserCode(), dto);
            dictItemService.modify(dto);
        }
    }

    private void logOperateDetails(OperateEnum operateEnum, String userCode, DictItemDto dto) {
        BaseBusyServiceUtil.addOperateLog(operateEnum, userCode, dto);
    }


    /**
     * 根据主键批量删除字典信息
     *
     * @param idList
     * @return
     */
    @RequestMapping(value = "dels")
    @ApiOperation(value = "根据主键批量删除字典项")
    @Authority(authous = {"dictType/dictTypeEdit"})
    public RestResponse dels(@RequestBody List<String> idList) {
        try {
            dictItemService.dels(idList);
            String logMessage = "删除字典项" + idList.toString() + "成功！";
            BaseBusyServiceUtil.addOperateLog(OperateEnum.removeDictItem, getUserCode(), logMessage);
            return RestResponse.success("字典项删除成功！");
        } catch (Exception e) {
            return RestResponse.failure("字典项删除失败：" + e.getMessage());
        }
    }
}
